<script lang="tsx" setup>
import { ref, nextTick, reactive, h, onBeforeMount } from "vue";
import {
  VxeFormPropTypes,
  VxeFormInstance,
  VxeModalInstance,
  VxeSelect,
  VxeButton,
  VxeInput
} from "vxe-pc-ui";
import { getSingle, addMerchant, getTemplates } from "@/api/project/project";
// import { getTemplates } from "@/api/merchant/project_template";
import { VxeUI } from "vxe-table";
let taxSourcesId = Number(sessionStorage.getItem("taxSourcesId"));
let merchantsInfoId = Number(sessionStorage.getItem("merchantsInfoId"));
const emits = defineEmits<{ (e: "reload"): void }>();
import { ElMessage } from "element-plus";
const vxeModalRef = ref<VxeModalInstance>();
const modalOptions = reactive<{
  modalValue: boolean;
  modalTitle: string;
  canSubmit: boolean;
}>({
  modalValue: false,
  modalTitle: "",
  canSubmit: true
});

const showModal = (title: string, canSubmit?: boolean): void => {
  modalOptions.modalTitle = title;
  modalOptions.modalValue = true;
  modalOptions.canSubmit = canSubmit ?? true;
};

interface AddProjectInput {
  type: number;
  contactMobile: string;
  contactName: string;
  endTime: string;
  startTime: string;
  estimatedCost: string;
  estimatedRequirements: number;
  estimatedUnit: string;
  mainBusiness: string;
  merchantsInfoId: number;
  merchantsDealId: number;
  projectContent: string;
  projectLocation: string;
  templateType: number;
  projectTemplateId: number | null;
  projectName: string;
  projectNameCurrent: string;
  projectSettlementRules: string;
  settlementCycle: number | null;
  taxSourcesId: number;
}
const formRef = ref<VxeFormInstance>();
const templateOptions = ref<any[]>();

const defaultFormData = () => {
  fileName.value = "";
  return {
    type: 1,
    contactMobile: "",
    contactName: "",
    endTime: "",
    startTime: "",
    time: "",
    estimatedCost: "",
    estimatedRequirements: 0,
    estimatedUnit: "",
    mainBusiness: "",
    merchantsInfoId: merchantsInfoId,
    projectContent: "",
    projectLocation: "",
    templateType: '',
    projectTemplateId: null,
    projectName: "",
    projectNameCurrent: "",
    projectSettlementRules: "",
    settlementCycle: null,
    taxSourcesId: taxSourcesId,
    uploadFilePaths: ""
  };
};
const fileName = ref("");
const formData = ref<AddProjectInput>(defaultFormData());
const formItems = ref<VxeFormPropTypes.Items>([
  {
    field: "type",
    title: "项目类型",
    span: 24,
    itemRender: {
      name: "$select",
      options: [
        { value: 1, label: "指定类型" },
        { value: 2, label: "大厅招募" }
      ]
    }
  },
  {
    field: "projectTemplateId",
    title: "模板名称",
    span: 24,
    slots: {
      default: ({ data }) => [
        h(VxeSelect, {
          options: templateOptions.value,
          optionProps: {
            value: "id",
            label: "projectName"
          },
          placeholder: "请选择模板",
          modelValue: data.projectTemplateId,
          onChange(v) {            
            // console.log(v,'请选择模板')
            data.projectTemplateId = v.value;
            data.templateType = v.value;
            data.projectNameCurrent = templateOptions.value.find(
              item => item.id === v.value
            ).projectName;
            data.projectContent = templateOptions.value.find(
              item => item.id === v.value
            ).projectContent;
            data.projectSettlementRules = templateOptions.value.find(
              item => item.id === v.value
            ).projectSettlementRules;
            data.projectLocation = templateOptions.value.find(
              item => item.id === v.value
            ).projectLocation;
          }
        })
      ]
    }
  },
  {
    field: "projectName",
    title: "项目名称",
    span: 24,
    itemRender: {
      name: "$input",
      props: { placeholder: "" }
    }
  },
  {
    field: "projectContent",
    title: "项目内容",
    span: 24,
    itemRender: {
      name: "$input",
      props: { disabled: true }
    }
  },  
  {
    field: "settlementCycle",
    title: "费用周期",
    span: 24,
    itemRender: {
      name: "$select",
      options: [
        { value: "1", label: "日结" },
        { value: "3", label: "周结" },
        { value: "2", label: "月结" }
      ],
      props: { placeholder: "请选择" }
    }
  },
  {
    field: "projectSettlementRules",
    title: "费用规则",
    span: 24,
    itemRender: {
      name: "$input",
      props: { disabled: true }
    }
  },
  {
    field: "projectLocation",
    title: "项目地点",
    span: 24,
    itemRender: {
      name: "$input",
      props: { disabled: true }
    }
  },
  {
    field: "contactName",
    title: "联系人",
    span: 24,
    itemRender: {
      name: "$input",
      props: { placeholder: "" }
    }
  },
  {
    field: "contactMobile",
    title: "联系方式",
    span: 24,
    itemRender: {
      name: "$input",
      props: { placeholder: "" }
    }
  },
  {
    field: "startTime",
    title: "开始时间",
    span: 24,
    itemRender: {
      name: "$input",
      props: { type: "date" }
    }
  },
  {
    field: "endTime",
    title: "结束时间",
    span: 24,
    itemRender: {
      name: "$input",
      props: { type: "date" }
    }
  },
  {
    field: "estimatedRequirements",
    title: "需求人数",
    span: 24,
    itemRender: {
      name: "$input"
    }
  },
  {
    field: "estimatedCost",
    title: "参考费用",
    span: 24,
    itemRender: {
      name: "$input"
    }
  },
  {
    field: "estimatedUnit",
    title: "费用单位",
    span: 24,
    itemRender: {
      name: "$select",
      options: [
        { value: "次", label: "次" },
        { value: "时", label: "时" },
        { value: "个", label: "个" }
      ],
      props: { placeholder: "请选择" }
    }
  },
  {
    field: "uploadOtherFiles",
    title: "项目附件",
    span: 24,
    slots: {
      default: ({ data }) => {
        return [
          h(VxeInput, {
            style: { width: `60%` },
            readonly: true,
            placeholder: "请选择文件",
            modelValue: fileName.value
          }),
          h(
            VxeButton,
            {
              style: { width: `24%` },
              async onClick() {
                try {
                  const { file } = await VxeUI.readFile({
                    types: [
                      "png",
                      "jpeg",
                      "jpg",
                      "xls",
                      "xlsx",
                      "doc",
                      "docx",
                      "pdf"
                    ]
                  });
                  data.file = file;
                  fileName.value = file.name;
                  formRef.value.validate();
                } catch (e) {}
              }
            },
            { default: () => "选择文件" }
          )
        ];
      }
    }
  }
]);
const formRules = ref<VxeFormPropTypes.Rules>({
  settlementCycle: [{ required: true, message: "请选择费用周期" }],
  projectName: [{ required: true, message: "请输入项目名称" }],
  estimatedCost: [{ required: true, message: "请输入参考费用" }],
  estimatedRequirements: [{ required: true, message: "请输入需求人数" }],
  contactName: [{ required: true, message: "请输入联系人" }],
  contactMobile: [{ required: true, message: "请输入联系方式" }],
  startTime: [{ required: true, message: "请输入开始时间" }],
  endTime: [{ required: true, message: "请输入结束时间" }],
  estimatedUnit: [{ required: true, message: "请选择费用单位" }]
});

const showAddModal = () => {
  showModal(`创建项目`);
  formData.value = defaultFormData();
  nextTick(() => {
    formRef.value.clearValidate();
  });
};
const showEditModal = (record: Recordable) => {
  showModal(`编辑项目->${record.title}`);
  nextTick(() => {
    formRef.value.clearValidate();
    // getSingle(record.id).then((data: any) => {
    //   formData.value = data;
    // });
  });
};
const showViewModal = (record: Recordable) => {
  showModal(`查看项目->${record.title}`, false);
  nextTick(() => {
    formRef.value.clearValidate();
    // getSingle(record.id).then((data: any) => {
    //   formData.value = data;
    // });
  });
};
const handleSubmit = async () => {
  const validate = await formRef.value.validate();
  if (!validate) {
    console.log(formData.value, "formData.value");
     formData.value.time = [formData.value.startTime, formData.value.endTime];
    formData.value.uploadFilePaths = fileName.value;
    addMerchant(formData.value).then(() => {      
      modalOptions.modalValue = false;
      emits("reload");
      ElMessage.success("操作成功");
    });
  }
};

onBeforeMount(() => {
  getTemplates({
    auditState: 1,
    merchantsDealState: 1,
    merchantsInfoId: merchantsInfoId,
    taxSourcesId: taxSourcesId
  }).then((result: any) => {
    if (result.code == 200) {
      templateOptions.value = result.data;
      console.log(templateOptions.value, "templateOptions.value");
    }
  });
});

defineExpose({ showAddModal, showEditModal, showViewModal });
</script>
<template>
  <vxe-modal
    ref="vxeModalRef"
    v-model="modalOptions.modalValue"
    width="800"
    height="750"
    showFooter
    :title="modalOptions.modalTitle"
  >
    <template #default>
      <vxe-form
        ref="formRef"
        :data="formData"
        :items="formItems"
        :rules="formRules"
        :titleWidth="100"
        :titleColon="true"
        :titleAlign="`right`"
      />
    </template>
    <template #footer>
      <vxe-button content="关闭" @click="modalOptions.modalValue = false" />
      <vxe-button
        v-if="modalOptions.canSubmit"
        status="primary"
        content="确定"
        @click="handleSubmit"
      />
    </template>
  </vxe-modal>
</template>
